<?php
class My_DataBase_Finder
{

    const RETURN_TYPE_ARRAY = 'array';

    /**
     * Associative array: condition => value
     * @var array
     */
    protected $conditions = array();

    /**
     * Table's name
     * @var string
     */
    protected $tableName;


    /**
     * Data type returned by the finder
     * @var string
     */
    protected $returnType = My_DataBase_Finder::RETURN_TYPE_ARRAY;

    /**
     * Limit
     * @var integer
     */
    protected $limit;

    /**
     * Order (like Zend_Db order)
     * @var string
     */
    protected $order;


    /**
     * @see Factory
     */
    protected function  __construct()
    {
        parent::__construct();
    }

    /**
     * @return My_Mapper_DataBase_Finder
     */
    public static function factory()
    {
        return new self();
    }

    /**
     * @param string $varName
     * @param mixed $value
     * @return My_Mapper_DataBase_Finder
     */
    public function addCondition($varName, $value)
    {
        $this->conditions[$varName] = $value;
        return $this;
    }

    /**
     * @param integer $integer
     * @return My_DataBase_Finder
     */
    public function limit($integer)
    {
        $this->limit = $integer;
        return $this;
    }

    /**
     * @param string $string
     * @return My_DataBase_Finder
     */
    public function order($string)
    {
        $this->order = $string;
        return $this;
    }

    /**
     * @param string $tableName
     * @return My_Mapper_DataBase_Finder
     */
    public function setTableName($tableName)
    {
        $this->tableName = $tableName;
        return $this;
    }

    /**
     * @param string $type
     * @return My_DataBase_Finder
     */
    public function setReturnType($type)
    {
        $this->returnType = $type;
        return $this;
    }

    /**
     * @return My_DataBase_Finder_Results
     */
    public function find()
    {
        $select = Zend_Db_Table::getDefaultAdapter()->select();
        $select->from( $this->tableName);
        foreach ($this->conditions as $var=>$value) $select->where($var. ' = ?', $value);
        if (!is_null($this->limit)) $select->limit ($this->limit);
        if (!is_null($this->order)) $select->order ($this->order);
        $result =  $select->query()->fetchAll();

        return My_DataBase_Finder_Results::factory()
            ->setReturnType($this->returnType)
            ->setContents($result);
    }
}
